package com.mahiru.mahiruaiagent.rag;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 编程学习助手文档加载器
 *
 * @Author Enkidu
 * @Date 2025/7/5 16:06
 */
@Slf4j
@Component
public class ChatAppDocumentLoader {
    // 构建资源解析器
    private final ResourcePatternResolver resourcePatternResolver;

    // 构造函数注入解析器
    public ChatAppDocumentLoader(ResourcePatternResolver resourcePatternResolver) {
        this.resourcePatternResolver = resourcePatternResolver;
    }

    /**
     * 加载多篇Markdown文档
     *
     * @return
     */
    public List<Document> loadMarkdowns() {
        List<Document> allDocuments = new ArrayList<>();
        try {
            // 加载所有Markdown文档
            Resource[] resources = resourcePatternResolver.getResources("classpath:document/*.md");
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                String learningStatus = extractContentWithinParentheses(filename);
                // 解析配置
                MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
                        .withHorizontalRuleCreateDocument(true)
                        .withIncludeBlockquote(false)
                        .withIncludeCodeBlock(false)
                        .withAdditionalMetadata("filename", filename)
                        .withAdditionalMetadata("learning_status", learningStatus)
                        .build();
                // 创建Markdown文档读取器
                MarkdownDocumentReader documentReader = new MarkdownDocumentReader(resource, config);
                allDocuments.addAll(documentReader.get());
            }
        } catch (IOException e) {
            log.error("加载Markdown文档失败", e);
        }
        return allDocuments;
    }

    /**
     * 提取字符串中括号内的内容
     *
     * @param filename 输入字符串
     * @return 括号内的内容
     */
    public static String extractContentWithinParentheses(String filename) {
        // 定义正则表达式
        String regex = ".*（(.*?)）\\.md$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(filename);

        // 查找匹配项
        if (matcher.find()) {
            // 返回第一个捕获组的内容
            return matcher.group(1);
        } else {
            // 没有找到匹配项
            return null;
        }
    }
}
